package com.hw.core.system.service;

import com.hw.core.system.entity.CourseType;
import com.hw.core.system.repository.CourseTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true)//全部方法只读事务
@CacheConfig(cacheNames = "courseType")
public class CourseTypeService {
    @Autowired
    private CourseTypeRepository courseTypeRepository;


    @Cacheable(key = "'list'")//缓存返回值，下次调用方法体不执行
    public List<CourseType> findAllCourseType() {
        return courseTypeRepository.findAll();
    }

    @Cacheable(key = "#id")
    public CourseType findCourseTypeById(Integer id) {
        return courseTypeRepository.findOne( id );
    }

    public List<CourseType> findCourseTypeByIdNotIN(List<CourseType> courseTypes) {
        List<Integer> ids = new ArrayList<>();

        for (CourseType courseType : courseTypes) {
            ids.add( courseType.getId() );
        }
        if (ids.size() > 0)
            return courseTypeRepository.findCourseTypeByIdNotIn( ids );
        else
            return courseTypeRepository.findAll();
    }


    @CacheEvict(allEntries = true)
    @Transactional
    public CourseType add(CourseType courseType) {
        return courseTypeRepository.save( courseType );
    }
    @CacheEvict(allEntries = true)
    @Transactional
    public void update(CourseType courseType) {
        CourseType one = courseTypeRepository.findOne( courseType.getId() );
        one.setName( courseType.getName() );
        one.setDescription( courseType.getDescription() );
    }
    @CacheEvict(allEntries = true)
    @Transactional
    public void delete(Integer id) {
        courseTypeRepository.delete( id );
    }
}
